<template>
  <view class="w-full">
    <!-- 选择器按钮 -->
    <view 
      class="relative w-full px-[32rpx] py-[28rpx] box-border bg-white rounded-[16rpx] border-2 transition-all duration-300 active:opacity-80"
      :class="displayText ? 'border-blue-500 shadow-md' : 'border-gray-200'"
      @click="openSelector"
    >
      <view class="flex items-center justify-between">
        <view class="flex-1 min-w-0 mr-[24rpx]">
          <text class="block text-[28rpx] font-medium mb-[6rpx]" :class="displayText ? 'text-gray-800' : 'text-gray-400'">
            {{ displayText || placeholder }}
          </text>
          <text v-if="displayText" class="block text-[24rpx] text-blue-500">点击重新选择</text>
          <text v-else class="block text-[24rpx] text-gray-400">请选择医院、科室和床位</text>
        </view>
        <view class="flex-shrink-0">
          <IconFont name="arrow-right" size="16" :color="displayText ? '#3b82f6' : '#9ca3af'" />
        </view>
      </view>
    </view>

    <!-- 选择器弹窗 -->
    <nut-popup v-model:visible="showSelector" position="bottom" :style="{ height: '75vh' }" round>
      <view class="h-full flex flex-col bg-gray-50">
        <!-- 标题栏 -->
        <view class="relative px-[32rpx] py-[28rpx] bg-white box-border border-b border-gray-100">
          <view class="flex items-center justify-between">
            <view class="flex-1">
              <text class="block text-[32rpx] font-bold text-gray-800 mb-[6rpx]">选择医院/科室/床位</text>
              <text class="block text-[24rpx] text-gray-500">请按步骤完成选择</text>
            </view>
            <view class="w-[48rpx] h-[48rpx] flex items-center justify-center active:opacity-60 transition-opacity" @click="closeSelector">
              <IconFont name="close" size="20" color="#9ca3af" />
            </view>
          </view>
        </view>

        <!-- 选择步骤指示器 -->
        <view class="px-[30rpx] py-[32rpx] box-border bg-white">
          <view class="flex items-center justify-between relative">
            <!-- 步骤1: 医院 -->
            <view class="flex flex-col items-center flex-1 relative z-10">
              <view 
                class="w-[56rpx] h-[56rpx] rounded-full flex items-center justify-center mb-[12rpx] transition-all duration-300"
                :class="currentStep >= 1 ? 'bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg' : 'bg-gray-200'"
              >
                <text class="text-[24rpx] font-bold" :class="currentStep >= 1 ? 'text-white' : 'text-gray-400'">
                  {{ currentStep > 1 ? '✓' : '1' }}
                </text>
              </view>
              <text class="text-[22rpx] font-medium" :class="currentStep >= 1 ? 'text-blue-600' : 'text-gray-400'">医院</text>
            </view>
            
            <!-- 连接线1 -->
            <view class="absolute top-[28rpx] left-[25%] right-[50%] h-[4rpx] rounded-full transition-all duration-300" 
                  :class="currentStep >= 2 ? 'bg-gradient-to-r from-blue-500 to-indigo-600' : 'bg-gray-200'"></view>
            
            <!-- 步骤2: 科室 -->
            <view class="flex flex-col items-center flex-1 relative z-10">
              <view 
                class="w-[56rpx] h-[56rpx] rounded-full flex items-center justify-center mb-[12rpx] transition-all duration-300"
                :class="currentStep >= 2 ? 'bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg' : 'bg-gray-200'"
              >
                <text class="text-[24rpx] font-bold" :class="currentStep >= 2 ? 'text-white' : 'text-gray-400'">
                  {{ currentStep > 2 ? '✓' : '2' }}
                </text>
              </view>
              <text class="text-[22rpx] font-medium" :class="currentStep >= 2 ? 'text-blue-600' : 'text-gray-400'">科室</text>
            </view>
            
            <!-- 连接线2 -->
            <view class="absolute top-[28rpx] left-[50%] right-[25%] h-[4rpx] rounded-full transition-all duration-300" 
                  :class="currentStep >= 3 ? 'bg-gradient-to-r from-blue-500 to-indigo-600' : 'bg-gray-200'"></view>
            
            <!-- 步骤3: 床位 -->
            <view class="flex flex-col items-center flex-1 relative z-10">
              <view 
                class="w-[56rpx] h-[56rpx] rounded-full flex items-center justify-center mb-[12rpx] transition-all duration-300"
                :class="currentStep >= 3 ? 'bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg' : 'bg-gray-200'"
              >
                <text class="text-[24rpx] font-bold" :class="currentStep >= 3 ? 'text-white' : 'text-gray-400'">
                  {{ currentStep > 3 ? '✓' : '3' }}
                </text>
              </view>
              <text class="text-[22rpx] font-medium" :class="currentStep >= 3 ? 'text-blue-600' : 'text-gray-400'">床位</text>
            </view>
          </view>
        </view>

        <!-- 选择内容区域 -->
        <view class="flex-1 overflow-hidden">
          <!-- 医院选择 -->
          <view v-if="currentStep === 1" class="h-full flex flex-col">
            <view class="px-[32rpx] py-[24rpx] bg-blue-50">
              <text class="block text-[28rpx] font-bold text-gray-800 mb-[4rpx]">请选择医院</text>
              <text class="block text-[24rpx] text-gray-500">{{ hospitalList.length > 0 ? '选择您要就诊的医院' : '请手动输入医院名称' }}</text>
            </view>
            
            <!-- 有选项数据：显示列表 -->
            <scroll-view v-if="hospitalList.length > 0" class="flex-1 px-[24rpx] pt-[16rpx] box-border" scroll-y>
              <view 
                v-for="hospital in hospitalList" 
                :key="hospital.key"
                class="mb-[16rpx] px-[28rpx] py-[24rpx] box-border bg-white rounded-[16rpx] border-2 transition-all duration-300 active:opacity-80"
                :class="selectedHospital?.key === hospital.key ? 'border-blue-500 shadow-md' : 'border-gray-100'"
                @click="selectHospital(hospital)"
              >
                <view class="flex items-center justify-between">
                  <view class="flex-1 min-w-0 mr-[24rpx]">
                    <text class="block text-[28rpx] font-bold mb-[6rpx]" :class="selectedHospital?.key === hospital.key ? 'text-blue-600' : 'text-gray-800'">
                      {{ hospital.title }}
                    </text>
                    <text class="block text-[24rpx]" :class="selectedHospital?.key === hospital.key ? 'text-blue-500' : 'text-gray-400'">
                      点击选择此医院
                    </text>
                  </view>
                  <view v-if="selectedHospital?.key === hospital.key" class="flex-shrink-0">
                    <IconFont name="Check" size="20" color="#3b82f6" />
                  </view>
                </view>
              </view>
            </scroll-view>
            
            <!-- 无选项数据：显示输入框 -->
            <view v-else class="flex-1 px-[32rpx] pt-[32rpx] box-border">
              <view class="bg-white rounded-[16rpx] border-2 border-blue-300 p-[24rpx] box-border">
                <text class="block text-[26rpx] text-gray-600 mb-[16rpx]">医院名称</text>
                <input
                  v-model="customHospitalInput"
                  class="w-full px-[24rpx] py-[20rpx] box-border bg-gray-50 rounded-[12rpx] text-[28rpx] border-2 border-gray-200 focus:border-blue-500"
                  placeholder="请输入医院名称"
                  placeholder-style="color: #9ca3af; font-size: 28rpx;"
                  @input="handleHospitalInput"
                />
                <text class="block text-[22rpx] text-gray-400 mt-[12rpx]">提示：输入后点击"下一步"继续</text>
              </view>
            </view>
          </view>

          <!-- 科室选择 -->
          <view v-if="currentStep === 2" class="h-full flex flex-col">
            <view class="px-[32rpx] py-[24rpx] bg-purple-50">
              <text class="block text-[28rpx] font-bold text-gray-800 mb-[4rpx]">请选择科室</text>
              <text class="block text-[24rpx] text-gray-500">{{ deptList.length > 0 ? '选择您要就诊的科室' : '请手动输入科室名称' }}</text>
            </view>
            
            <!-- 有选项数据：显示列表 -->
            <scroll-view v-if="deptList.length > 0" class="flex-1 px-[24rpx] pt-[16rpx] box-border" scroll-y>
              <view 
                v-for="dept in deptList" 
                :key="dept.key"
                class="mb-[16rpx] px-[28rpx] py-[24rpx] box-border bg-white rounded-[16rpx] border-2 transition-all duration-300 active:opacity-80"
                :class="selectedDept?.key === dept.key ? 'border-purple-500 shadow-md' : 'border-gray-100'"
                @click="selectDept(dept)"
              >
                <view class="flex items-center justify-between">
                  <view class="flex-1 min-w-0 mr-[24rpx]">
                    <text class="block text-[28rpx] font-bold mb-[6rpx]" :class="selectedDept?.key === dept.key ? 'text-purple-600' : 'text-gray-800'">
                      {{ dept.title }}
                    </text>
                    <text class="block text-[24rpx]" :class="selectedDept?.key === dept.key ? 'text-purple-500' : 'text-gray-400'">
                      点击选择此科室
                    </text>
                  </view>
                  <view v-if="selectedDept?.key === dept.key" class="flex-shrink-0">
                    <IconFont name="Check" size="20" color="#a855f7" />
                  </view>
                </view>
              </view>
            </scroll-view>
            
            <!-- 无选项数据：显示输入框 -->
            <view v-else class="flex-1 px-[32rpx] pt-[32rpx] box-border">
              <view class="bg-white rounded-[16rpx] border-2 border-purple-300 p-[24rpx] box-border">
                <text class="block text-[26rpx] text-gray-600 mb-[16rpx]">科室名称</text>
                <input
                  v-model="customDeptInput"
                  class="w-full px-[24rpx] py-[20rpx] box-border bg-gray-50 rounded-[12rpx] text-[28rpx] border-2 border-gray-200 focus:border-purple-500"
                  placeholder="请输入科室名称"
                  placeholder-style="color: #9ca3af; font-size: 28rpx;"
                  @input="handleDeptInput"
                />
                <text class="block text-[22rpx] text-gray-400 mt-[12rpx]">提示：输入后点击"下一步"继续</text>
              </view>
            </view>
          </view>

          <!-- 床位选择 -->
          <view v-if="currentStep === 3" class="h-full flex flex-col">
            <view class="px-[32rpx] py-[24rpx] bg-green-50">
              <text class="block text-[28rpx] font-bold text-gray-800 mb-[4rpx]">请选择床位</text>
              <text class="block text-[24rpx] text-gray-500">{{ bedList.length > 0 ? '选择您的床位号' : '请手动输入床位号' }}</text>
            </view>
            
            <!-- 有选项数据：显示列表 -->
            <scroll-view v-if="bedList.length > 0" class="flex-1 px-[24rpx] pt-[16rpx] box-border" scroll-y>
              <view 
                v-for="bed in bedList" 
                :key="bed.id"
                class="mb-[16rpx] px-[28rpx] py-[24rpx] box-border bg-white rounded-[16rpx] border-2 transition-all duration-300 active:opacity-80"
                :class="selectedBed?.id === bed.id ? 'border-green-500 shadow-md' : 'border-gray-100'"
                @click="selectBed(bed)"
              >
                <view class="flex items-center justify-between">
                  <view class="flex-1 min-w-0 mr-[24rpx]">
                    <text class="block text-[28rpx] font-bold mb-[6rpx]" :class="selectedBed?.id === bed.id ? 'text-green-600' : 'text-gray-800'">
                      {{ bed.name }}
                    </text>
                    <text class="block text-[24rpx]" :class="selectedBed?.id === bed.id ? 'text-green-500' : 'text-gray-400'">
                      床位编号: {{ bed.code }}
                    </text>
                  </view>
                  <view v-if="selectedBed?.id === bed.id" class="flex-shrink-0">
                    <IconFont name="Check" size="20" color="#22c55e" />
                  </view>
                </view>
              </view>
            </scroll-view>
            
            <!-- 无选项数据：显示输入框 -->
            <view v-else class="flex-1 px-[32rpx] pt-[32rpx] box-border">
              <view class="bg-white rounded-[16rpx] border-2 border-green-300 p-[24rpx] box-border">
                <text class="block text-[26rpx] text-gray-600 mb-[16rpx]">床位号</text>
                <input
                  v-model="customBedInput"
                  class="w-full px-[24rpx] py-[20rpx] box-border bg-gray-50 rounded-[12rpx] text-[28rpx] border-2 border-gray-200 focus:border-green-500"
                  placeholder="请输入床位号"
                  placeholder-style="color: #9ca3af; font-size: 28rpx;"
                  @input="handleBedInput"
                />
                <text class="block text-[22rpx] text-gray-400 mt-[12rpx]">提示：输入后点击"确定选择"完成</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 底部操作按钮 -->
        <view class="px-[32rpx] py-[24rpx] bg-white border-t border-gray-100 safe-area-inset-bottom box-border">
          <view class="flex gap-[16rpx]">
            <!-- 上一步按钮 -->
            <view 
              v-if="currentStep > 1"
              class="flex-1 h-90rpx rounded-16rpx bg-white border-2 border-gray-200 flex items-center justify-center transition-all duration-300 active:opacity-70 box-border"
              @click="goBack"
            >
              <IconFont name="rect-left" size="16" color="#6b7280" class="mr-[8rpx]" />
              <text class="text-[30rpx] font-semibold text-gray-700">上一步</text>
            </view>
            <!-- 下一步/确定按钮 -->
            <view 
              :class="[
                'h-90rpx rounded-16rpx flex items-center justify-center transition-all duration-300 box-border',
                currentStep > 1 ? 'flex-1' : 'w-full',
                canProceed ? 'bg-blue-500 active:opacity-80' : 'bg-gray-300 opacity-50'
              ]"
              @click="goNext"
            >
              <text class="text-[30rpx] font-semibold text-white mr-[8rpx]">
                {{ currentStep === 3 ? '确定选择' : '下一步' }}
              </text>
              <IconFont v-if="currentStep === 3" name="Check" size="16" color="#ffffff" />
              <IconFont v-else name="rect-right" size="16" color="#ffffff" />
            </view>
          </view>
        </view>
      </view>
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { request } from '@/service/request'
import { IconFont } from '@nutui/icons-vue-taro'

// 类型定义
interface Hospital {
  key: string
  title: string
  value: any
  parentId: string
  children: any
  leaf: boolean
}

interface Department {
  key: string
  leaf: boolean
  parentId: string
  title: string
}

interface Bed {
  code: string
  deptId: string
  id: string
  name: string
}

interface SelectedData {
  hospital: Hospital | null
  department: Department | null
  bed: Bed | null
}

// Props
interface Props {
  placeholder?: string
  modelValue?: SelectedData
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '请选择医院/科室/床位'
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: SelectedData]
  'confirm': [value: SelectedData]
}>()

// 响应式数据
const showSelector = ref(false)
const currentStep = ref(1)
const loading = ref(false)

// 数据列表
const hospitalList = ref<Hospital[]>([])
const deptList = ref<Department[]>([])
const bedList = ref<Bed[]>([])

// 选中的数据
const selectedHospital = ref<Hospital | null>(null)
const selectedDept = ref<Department | null>(null)
const selectedBed = ref<Bed | null>(null)

// 自定义输入数据
const customHospitalInput = ref('')
const customDeptInput = ref('')
const customBedInput = ref('')

// 计算属性
const displayText = computed(() => {
  if (selectedHospital.value && selectedDept.value && selectedBed.value) {
    return `${selectedHospital.value.title} - ${selectedDept.value.title} - ${selectedBed.value.name}`
  }
  return ''
})

const canProceed = computed(() => {
  switch (currentStep.value) {
    case 1:
      // 有选项：检查是否选中；无选项：检查是否输入
      return hospitalList.value.length > 0 
        ? selectedHospital.value !== null 
        : customHospitalInput.value.trim() !== ''
    case 2:
      return deptList.value.length > 0 
        ? selectedDept.value !== null 
        : customDeptInput.value.trim() !== ''
    case 3:
      return bedList.value.length > 0 
        ? selectedBed.value !== null 
        : customBedInput.value.trim() !== ''
    default:
      return false
  }
})

// 方法
const openSelector = () => {
  showSelector.value = true
  // 重置选择状态
  currentStep.value = 1
  selectedHospital.value = null
  selectedDept.value = null
  selectedBed.value = null
  deptList.value = []
  bedList.value = []
  
  // 清空所有输入框内容
  customHospitalInput.value = ''
  customDeptInput.value = ''
  customBedInput.value = ''
  
  // 加载医院列表
  loadHospitalList()
}

const closeSelector = () => {
  showSelector.value = false
}

const loadHospitalList = async () => {
  try {
    loading.value = true
    const res = await request.get(
      '/nurse_hospital/nurseHospital/loadTreeChildren?pid=0',
      {},
      { useErrMsg: true }
    )
    hospitalList.value = res.success || [
      {
        key: '1903976907498213377',
        title: '南宁市邕宁区人民医院',
        value: null,
        parentId: '0',
        children: null,
        leaf: true,
      },
    ]
  } catch (error) {
    console.error('加载医院列表失败:', error)
    hospitalList.value = []
  } finally {
    loading.value = false
  }
}

const loadDeptList = async (hospitalId: string) => {
  try {
    loading.value = true
    const res = await request.get(
      `/nurse_dept/nurseDept/loadTreeChildrenByHisid?pid=0&hospitalId=${hospitalId}`,
      {},
      { useErrMsg: true }
    )
    deptList.value = res.success || [
      {
        key: '1902262229508272129',
        leaf: true,
        parentId: '0',
        title: '护理科',
      },
    ]
  } catch (error) {
    console.error('加载科室列表失败:', error)
    deptList.value = []
  } finally {
    loading.value = false
  }
}

const loadBedList = async (deptId: string) => {
  try {
    loading.value = true
    const res = await request.get(
      `/nurse_bed/nurseBed/queryByDeptId?deptId=${deptId}`,
      {},
      { useErrMsg: true }
    )
    bedList.value = res.success || [
      {
        code: 'HL001',
        deptId: '1902262229508272129',
        id: '1902262323662008322',
        name: '护理001',
      },
    ]
  } catch (error) {
    console.error('加载床位列表失败:', error)
    bedList.value = []
  } finally {
    loading.value = false
  }
}

// 输入框处理方法
const handleHospitalInput = () => {
  // 输入时清除选中状态
  if (customHospitalInput.value.trim()) {
    selectedHospital.value = null
  }
}

const handleDeptInput = () => {
  if (customDeptInput.value.trim()) {
    selectedDept.value = null
  }
}

const handleBedInput = () => {
  if (customBedInput.value.trim()) {
    selectedBed.value = null
  }
}

const selectHospital = async (hospital: Hospital) => {
  selectedHospital.value = hospital
  customHospitalInput.value = '' // 清空输入框
  selectedDept.value = null
  selectedBed.value = null
  deptList.value = []
  bedList.value = []
  
  // 加载科室列表
  await loadDeptList(hospital.key)
  currentStep.value = 2
}

const selectDept = async (dept: Department) => {
  selectedDept.value = dept
  customDeptInput.value = '' // 清空输入框
  selectedBed.value = null
  bedList.value = []
  
  // 加载床位列表
  await loadBedList(dept.key)
  currentStep.value = 3
}

const selectBed = (bed: Bed) => {
  selectedBed.value = bed
  customBedInput.value = '' // 清空输入框
}

const goBack = () => {
  if (currentStep.value > 1) {
    currentStep.value--
  }
}

const goNext = async () => {
  if (!canProceed.value) return
  
  if (currentStep.value < 3) {
    // 处理自定义输入的情况
    if (currentStep.value === 1 && hospitalList.value.length === 0 && customHospitalInput.value.trim()) {
      // 创建自定义医院对象
      selectedHospital.value = {
        key: 'custom-hospital',
        title: customHospitalInput.value.trim(),
        value: null,
        parentId: '0',
        children: null,
        leaf: true
      }
      // 清空科室和床位数据，下一步需要手动输入
      deptList.value = []
      bedList.value = []
      currentStep.value = 2
    } else if (currentStep.value === 2 && deptList.value.length === 0 && customDeptInput.value.trim()) {
      // 创建自定义科室对象
      selectedDept.value = {
        key: 'custom-dept',
        title: customDeptInput.value.trim(),
        leaf: true,
        parentId: selectedHospital.value?.key || '0'
      }
      // 清空床位数据，下一步需要手动输入
      bedList.value = []
      currentStep.value = 3
    } else {
      currentStep.value++
    }
  } else {
    // 处理最后一步的自定义输入
    if (bedList.value.length === 0 && customBedInput.value.trim()) {
      selectedBed.value = {
        id: 'custom-bed',
        name: customBedInput.value.trim(),
        code: customBedInput.value.trim(),
        deptId: selectedDept.value?.key || ''
      }
    }
    
    // 确认选择
    const selectedData: SelectedData = {
      hospital: selectedHospital.value,
      department: selectedDept.value,
      bed: selectedBed.value
    }
    
    emit('update:modelValue', selectedData)
    emit('confirm', selectedData)
    closeSelector()
  }
}

// 初始化
onMounted(() => {
  if (props.modelValue) {
    selectedHospital.value = props.modelValue.hospital
    selectedDept.value = props.modelValue.department
    selectedBed.value = props.modelValue.bed
  }
})
</script>

